<template>
  <Dialog
    :visible="visible"
    modal
    header="编辑用户"
    :style="{ width: '600px' }"
    :closable="true"
    :draggable="false"
    @update:visible="$emit('update:visible', $event)"
    @hide="handleClose"
  >
    <div class="user-form">
      <form @submit.prevent="handleSubmit">
        <div class="form-row">
          <div class="form-item">
            <label class="form-label required">用户名</label>
            <InputText
              v-model="formData.username"
              placeholder="请输入用户名"
              :class="{ 'p-invalid': errors.username }"
            />
            <small v-if="errors.username" class="p-error">{{ errors.username }}</small>
          </div>
          
          <div class="form-item">
            <label class="form-label required">昵称</label>
            <InputText
              v-model="formData.nickname"
              placeholder="请输入昵称"
              :class="{ 'p-invalid': errors.nickname }"
            />
            <small v-if="errors.nickname" class="p-error">{{ errors.nickname }}</small>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label required">邮箱</label>
            <InputText
              v-model="formData.email"
              placeholder="请输入邮箱"
              :class="{ 'p-invalid': errors.email }"
            />
            <small v-if="errors.email" class="p-error">{{ errors.email }}</small>
          </div>
          
          <div class="form-item">
            <label class="form-label">手机号</label>
            <InputText
              v-model="formData.phone"
              placeholder="请输入手机号"
              :class="{ 'p-invalid': errors.phone }"
            />
            <small v-if="errors.phone" class="p-error">{{ errors.phone }}</small>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">新密码</label>
            <Password
              v-model="formData.password"
              placeholder="留空则不修改密码"
              :class="{ 'p-invalid': errors.password }"
              toggle-mask
              :feedback="false"
            />
            <small v-if="errors.password" class="p-error">{{ errors.password }}</small>
          </div>
          
          <div class="form-item">
            <label class="form-label">确认新密码</label>
            <Password
              v-model="formData.confirmPassword"
              placeholder="请确认新密码"
              :class="{ 'p-invalid': errors.confirmPassword }"
              toggle-mask
              :feedback="false"
            />
            <small v-if="errors.confirmPassword" class="p-error">{{ errors.confirmPassword }}</small>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">状态</label>
            <Dropdown
              v-model="formData.status"
              :options="statusOptions"
              option-label="label"
              option-value="value"
              placeholder="请选择状态"
              size="small"
            />
          </div>
          
          <div class="form-item">
            <label class="form-label">角色</label>
            <MultiSelect
              v-model="formData.roles"
              :options="roleOptions"
              option-label="label"
              option-value="value"
              placeholder="请选择角色"
              :max-selected-labels="3"
              size="small"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item full-width">
            <label class="form-label">备注</label>
            <Textarea
              v-model="formData.remark"
              placeholder="请输入备注"
              :rows="3"
              :auto-resize="true"
            />
          </div>
        </div>
      </form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <Button
          label="取消"
          severity="secondary"
          @click="handleClose"
          :disabled="loading"
        />
        <Button
          label="确定"
          severity="primary"
          @click="handleSubmit"
          :loading="loading"
        />
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import Dialog from 'primevue/dialog'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import Password from 'primevue/password'
import Dropdown from 'primevue/dropdown'
import MultiSelect from 'primevue/multiselect'
import Textarea from 'primevue/textarea'

interface UserData {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  status: number
  roles: string[]
  remark?: string
}

interface Props {
  visible: boolean
  userData?: UserData | null
  loading?: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: any): void
  (e: 'close'): void
}

const props = withDefaults(defineProps<Props>(), {
  userData: null,
  loading: false
})

const emit = defineEmits<Emits>()

// 表单数据
const formData = reactive({
  id: 0,
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  status: 1,
  roles: [],
  remark: ''
})

// 表单验证错误
const errors = reactive({
  username: '',
  nickname: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: ''
})

// 状态选项
const statusOptions = [
  { label: '启用', value: 1 },
  { label: '禁用', value: 0 }
]

// 角色选项
const roleOptions = [
  { label: '管理员', value: 'admin' },
  { label: '普通用户', value: 'user' },
  { label: '访客', value: 'guest' }
]

// 监听visible和userData变化
watch([() => props.visible, () => props.userData], ([newVisible, newUserData]) => {
  if (newVisible && newUserData) {
    loadUserData(newUserData)
  } else if (newVisible) {
    resetForm()
  }
})

// 加载用户数据
const loadUserData = (userData: UserData) => {
  Object.assign(formData, {
    id: userData.id,
    username: userData.username,
    nickname: userData.nickname,
    email: userData.email,
    phone: userData.phone || '',
    password: '',
    confirmPassword: '',
    status: userData.status,
    roles: Array.isArray(userData.roles) ? userData.roles : [],
    remark: userData.remark || ''
  })
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: 0,
    username: '',
    nickname: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    status: 1,
    roles: [],
    remark: ''
  })
  
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
}

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 重置错误信息
  Object.keys(errors).forEach(key => {
    errors[key as keyof typeof errors] = ''
  })
  
  // 用户名验证
  if (!formData.username.trim()) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (formData.username.length < 2) {
    errors.username = '用户名至少2个字符'
    isValid = false
  }
  
  // 昵称验证
  if (!formData.nickname.trim()) {
    errors.nickname = '请输入昵称'
    isValid = false
  }
  
  // 邮箱验证
  if (!formData.email.trim()) {
    errors.email = '请输入邮箱'
    isValid = false
  } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
    errors.email = '请输入正确的邮箱格式'
    isValid = false
  }
  
  // 手机号验证
  if (formData.phone && !/^1[3-9]\d{9}$/.test(formData.phone)) {
    errors.phone = '请输入正确的手机号格式'
    isValid = false
  }
  
  // 密码验证（编辑时密码是可选的）
  if (formData.password && formData.password.length < 6) {
    errors.password = '密码至少6个字符'
    isValid = false
  }
  
  // 确认密码验证
  if (formData.password && formData.password !== formData.confirmPassword) {
    errors.confirmPassword = '两次输入的密码不一致'
    isValid = false
  }
  
  return isValid
}

// 处理提交
const handleSubmit = () => {
  if (!validateForm()) {
    return
  }
  
  const submitData = {
    ...formData,
    roles: formData.roles.join(',')
  }
  
  // 如果密码为空，则不包含在提交数据中
  if (!formData.password) {
    delete submitData.password
    delete submitData.confirmPassword
  }
  
  emit('submit', submitData)
}

// 处理关闭
const handleClose = () => {
  emit('update:visible', false)
  emit('close')
}
</script>

<style scoped>
.user-form {
  padding: 20px 0;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-item.full-width {
  flex: 1 1 100%;
}

.form-label {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.form-label.required::after {
  content: ' *';
  color: #ff4d4f;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表单组件样式覆盖 */
:deep(.p-inputtext),
:deep(.p-password),
:deep(.p-dropdown),
:deep(.p-multiselect),
:deep(.p-inputtextarea) {
  height: 40px;
  font-size: 14px;
}

:deep(.p-inputtextarea) {
  height: auto;
  min-height: 80px;
}

:deep(.p-password .p-inputtext) {
  height: 40px;
}

:deep(.p-error) {
  font-size: 12px;
  margin-top: 4px;
}

/* 下拉框选项字体样式 */
:deep(.p-dropdown-panel .p-dropdown-items .p-dropdown-item) {
  font-size: 14px !important;
  line-height: 20px !important;
  padding: 8px 12px !important;
}

:deep(.p-multiselect-panel .p-multiselect-items .p-multiselect-item) {
  font-size: 14px !important;
  line-height: 20px !important;
  padding: 8px 12px !important;
}

/* 下拉框placeholder样式 */
:deep(.p-dropdown .p-dropdown-label.p-placeholder) {
  font-size: 14px !important;
  line-height: 20px !important;
  color: #6c757d !important;
}

:deep(.p-multiselect .p-multiselect-label.p-placeholder) {
  font-size: 14px !important;
  line-height: 20px !important;
  color: #6c757d !important;
}
</style>
